package com.sz.youban.controller.allinpay;

import com.sz.youban.controller.base.BaseController;
import com.sz.youban.dt.entity.result.ResultData;
import com.sz.youban.dt.entity.result.ResultDataEnum;
import com.sz.youban.dt.entity.result.ResultModel;
import com.sz.youban.dt.interfs.allinpay.AllinpayService;
import com.sz.youban.dt.model.AllinpayReceiveRequest;
import com.sz.youban.dt.model.AuthenticationRequest;
import com.sz.youban.dt.model.PairDef;
import com.sz.youban.dt.service.allinpay.helpper.AllinpayUtil;
import com.sz.youban.dt.service.utils.ShaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;




/**
 * Created by liyang on 2017/6/12.
 */
@RestController
@RequestMapping("/allinpay")
public class AllinpayController extends BaseController {
    @Value("${develop}")
    private boolean develop;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AllinpayService allinpayService;

    /**
     * 单笔实时代收
     */
    @PostMapping(value="receiveAndPay",consumes="application/json")
    public ResultModel receiveAndPay(@RequestBody AllinpayReceiveRequest allinpayReceiveRequest, HttpServletRequest request){
        log.info("----- 进入receiveAndPay接口，请求参数为  -----{}" , allinpayReceiveRequest.toString());

        //1，==========校验接口请求参数和交易类型==========
        if( !AllinpayUtil.checkreceiveAndPayParam(allinpayReceiveRequest) ){
            log.info("----------receiveAndPay请求，必要参数不足");
            return success(ResultDataEnum.PARAMS_ERROR);
        }else if ( !AllinpayUtil.checkreceiveAndPayTrxCode(allinpayReceiveRequest) ){
            log.info("----------receiveAndPay请求，交易类型错误");
            return success(ResultDataEnum.TRXCODE_ERROR);
        }

        //2，==========对请求参数进行SHA加密产生 keySHA==========
        String key = AllinpayUtil.receiveBulidKey(allinpayReceiveRequest);

        log.info("--------加密前的key为：  {}",key);
        String keySHA = "";
        try {
            keySHA = ShaUtil.encryptSHA(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("----------加密后的key为：  {}",keySHA);

        //3，==========获取请求头信息，进行SHA签名校验==========
        String secretKey = request.getHeader("key");
        log.info("----------请求头传来的secretKey为：{}", secretKey);
        if( !keySHA.equals(secretKey)){      //对比签名
            log.info("----------SHA签名失败");
            return success(ResultDataEnum.KEY_ERROR);
        }

        //4，==========整理参数请求通联，并存储交易记录==========
        if(develop){       //如果是测试环境，直接mock为交易成功
            return success();
        }
        ResultData resultData = null;
        try {
            resultData = allinpayService.singleTranxReceivePay(allinpayReceiveRequest.getBankCode(),allinpayReceiveRequest.getAccountNo(),allinpayReceiveRequest.getAccountName(),
                    allinpayReceiveRequest.getAmount(),allinpayReceiveRequest.getUserId(),allinpayReceiveRequest.getPhone(),allinpayReceiveRequest.getProvince(),
                    allinpayReceiveRequest.getCity(), allinpayReceiveRequest.getCardId(),allinpayReceiveRequest.getTrxCode(),allinpayReceiveRequest.getChannel(),
                    allinpayReceiveRequest.getOrderNo(), allinpayReceiveRequest.getInvokeUrl());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //5，==========组装返回给app的参数==========
        //格式 {"ret":200,"milliUse":520,"message":"OK","content":{"code":10000,"msg":"ok","info":""}}
        //交易代码。100011是实时单笔代收，100014是实时单笔代付
//        if(GV.i(allinpayReceiveRequest.getTrxCode()) == PayType.RECEIVED_TIME.getCode()){
//        	resultData.setInfo("单笔实时代收请求成功！");
//        }else if(GV.i(allinpayReceiveRequest.getTrxCode()) == PayType.PAYED_TIME.getCode()){
//        	resultData.setInfo("单笔实时代付请求成功！");
//        }

        //这里是根据前端的需求，将交易成功的返回码，由原来的100替换成10000
        if(resultData.getCode() == 100){
            resultData.setCode(10000);
        }

        log.info("----- receiveAndPay接口结束，返回的响应数据为： {}" , resultData.toString());
        return success(resultData);
    }


    /**
     * 三要素认证接口
     */
    @PostMapping(value="authentication",consumes="application/json")
    public ResultModel authentication(@RequestBody AuthenticationRequest authenticationRequest, HttpServletRequest request){
        log.info("----- authentication 接口请求参数 -----{}" , authenticationRequest.toString());

        //==========1，校验接口请求参数和交易类型==========
        if( !AllinpayUtil.checkAuthenticationParam(authenticationRequest) ){
            log.info("----------authentication，必要参数不足");
            return success(ResultDataEnum.PARAMS_ERROR);
        }

        //2，==========对请求参数，进行SHA加密产生 keySHA==========
        String key = AllinpayUtil.authenticationBulidKey(authenticationRequest);
        log.info("--------加密前的key为：  {}",key);
        String keySHA = "";
        try {
            keySHA = ShaUtil.encryptSHA(key.trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("----------加密后的key为：  {}",keySHA);

        //3，==========获取请求头信息，进行SHA签名校验==========
        String secretKey = request.getHeader("key");
        log.info("----------请求头传来的secretKey为：{}", secretKey);
        if( !keySHA.equals(secretKey)){      //对比签名
            log.info("----------SHA签名失败");
            return success(ResultDataEnum.KEY_ERROR);
        }

        //4，==========整理参数请求通联，并存储交易记录==========
//        allinpayService.authentication(url, idCard, name, bankCard, mechantNo,dealKey, dealNo);
        PairDef<ResultData, Map<String, String>> pd = allinpayService.authentication(authenticationRequest.getCardId(), 
        		authenticationRequest.getAccountName(), authenticationRequest.getAccountNo() , authenticationRequest.getPhone());
        ResultData resultData = pd.getFirst();

        //5，==========组装返回给app的参数==========
        //这里是根据前端的需求，讲交易成功的返回码，由原来的100替换成10000
        if(resultData.getCode() == 300){
        	resultData.setCode(10000);
        }
        resultData.setInfo(pd.getSecond());
        log.info("---------- authentication接口结束，返回的响应数据为: {}" ,resultData);
        return success(resultData);

    }

}
